package listbyorder.access901_1000.test931;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/8/20 17:06
 */
public class Solution1 {

    int res = Integer.MAX_VALUE;

    public int minFallingPathSum(int[][] A) {
        if (A == null || A.length == 0 || A[0].length == 0) return 0;
        int n = A.length;
        int[][] dp = new int[n][n];
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < n; j++) {
                if (i == n - 1) {
                    dp[i][j] = A[i][j];
                } else {
                    if (j == 0) {
                        dp[i][j] = Math.min(dp[i + 1][j], dp[i + 1][j + 1]) + A[i][j];
                    } else if (j == n - 1) {
                        dp[i][j] = Math.min(dp[i + 1][j], dp[i + 1][j - 1]) + A[i][j];
                    } else {
                        dp[i][j] = Math.min(dp[i + 1][j], Math.min(dp[i + 1][j - 1], dp[i + 1][j + 1])) + A[i][j];
                    }
                }
                if (i == 0) {
                    res = Math.min(res, dp[i][j]);
                }
            }
        }
        return res;
    }
}
